package com.mega.fe.util.vm;

import com.mega.fe.util.MEGA;
import com.mega.fe.util.UnsafeUtil;
import com.sun.tools.attach.VirtualMachine;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Field;

public class VMSetter {
    public static long CURRENT_PID;
    public static VirtualMachine CURRENT_VM = null;

    static {
        String jvmPID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
        CURRENT_PID = Long.parseLong(jvmPID);
        MEGA.jvmPID = jvmPID;
        System.out.println(CURRENT_PID);
        try {
            enableAttachSelf();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    public static void attachAndLoad() throws Throwable{

        VMSetter.CURRENT_VM = VirtualMachine.attach(String.valueOf(CURRENT_PID));
        Class<?> clazz = Class.forName("sun.instrument.InstrumentationImpl", false, null);
        MethodHandle loadAgent = MEGA.IMPL_LOOKUP().findStatic(clazz, "loadAgent", MethodType.methodType(void.class, String.class));
        String jarPath = MEGA.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        //String real = jarPath.substring(jarPath.indexOf(":")+1, jarPath.indexOf("!"));
        File file = FileUtils.getFile("mods/fe-1.20.1.jar");
        String str = file.exists() ? jarPath+"fe-1.20.1.jar" : "E:\\CollapsingWorld\\System-e\\FE\\build\\libs\\fe-1.20.1.jar";
        System.out.println(str);
        //loadAgent.invoke(str);
        //VMSetter.CURRENT_VM.loadAgent(str);
        //loadAgent.invoke( file.exists() ? jarPath+"fe-1.20.1.jar" : "D:\\CollapsingWorld\\System-e\\FE\\build\\libs\\fe-1.20.1.jar");
        VMSetter.CURRENT_VM.detach();
    }

    public static boolean compressPtr() {return true;}

    public static boolean isHotSpot() {
        return true;
    }
    public static void enableAttachSelf() throws Throwable{
        if (isHotSpot()) {
            Class<?> HotSpotVm = Class.forName("sun.tools.attach.HotSpotVirtualMachine");
            Field field = HotSpotVm.getDeclaredField("ALLOW_ATTACH_SELF");
            UnsafeUtil unsafeUtil = new UnsafeUtil(HotSpotVm);
            unsafeUtil.set(field, true);
        }
    }
}
